package com.bookocean.controller;
import com.bookocean.application.common.Result;
import com.bookocean.application.exception.BusinessException;
import com.bookocean.application.exception.WeChatErrorCodeEnum;
import com.bookocean.application.service.UserInfoService;
import com.bookocean.controller.dto.UserInfoDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 *
 * @author 简语
 * @since 2025-01-27
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserInfoService userService;

    /**
     * 微信登录接口
     *
     * @param request 包含 code 的请求体
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<UserInfoDto> login(@RequestBody Map<String, String> request) {
        try {
            String code = request.get("code");
            if (code == null || code.trim().isEmpty()) {
                return Result.error("登录凭证不能为空");
            }
            log.info("收到微信登录请求，code: {}", code);
            UserInfoDto userInfo = userService.login(code);
            // 不返回密钥信息
            userInfo.setSessionKey("");
            log.info("登录成功，返回数据: openid={}, accessToken={}, userId={}", userInfo.getOpenid(), userInfo.getAccessToken(),
                    userInfo.getId());
            return Result.success(userInfo);

        } catch (Exception e) {
            throw new BusinessException(WeChatErrorCodeEnum.BOOK_OCEAN_GET_USER_INFO_ERROR);
        }
    }

    /**
     * 修改用户接口
     *
     * @param  userInfoDto
     * @return 用户信息
     */
    @PostMapping("/updateUserAvatar")
    public Result<UserInfoDto> updateUserAvatar(@RequestBody UserInfoDto userInfoDto) {
        try {
            log.info("收到修改用户请求: {}", userInfoDto);
            UserInfoDto userInfo = userService.updateUserAvatar(userInfoDto);
            return Result.success(userInfo);

        } catch (Exception e) {
            throw new BusinessException(WeChatErrorCodeEnum.UPDATE_USER_INFO_ERROR);
        }
    }


}
